package com.whccb.apps.office.document.event.receive.system;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.listener.ExecuteListener;
import com.actionsoft.bpms.commons.formfile.model.delegate.FormFile;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.server.fs.DCContext;
import com.actionsoft.bpms.server.fs.dc.DCProfileManager;
import com.actionsoft.bpms.util.ConsolePrinter;
import com.actionsoft.sdk.local.SDK;
import com.whccb.apps.office.document.util.ODAppUtil;

public class Test extends ExecuteListener {

	public String getDescription() {
		return "测试";
	}

	public String getProvider() {
		return "ActionSoft";
	}

	public String getVersion() {
		return "AWS 6.0";
	}

	@Override
	public void execute(ProcessExecutionContext pec) throws Exception {
		BO bo = SDK.getBOAPI().getByProcess("BO_WHBK_OD_INSTITUTION",
				pec.getProcessInstance().getId());
		if (bo != null) {
			String a = toGrcXmlContext(bo);
			System.out.println("a=" + a);
			String reg_level_dict = bo.getString("REG_LEVEL_DICT");
			FormFile formFile = null;
			if ("04".equals(reg_level_dict)) {// 体系文件，不套红，直接将原文件即附件返回
				List<FormFile> formFiles = SDK.getBOAPI().getFiles(bo.getId(),
						"ATTFILE");
				if (formFiles != null && !formFiles.isEmpty()
						&& formFiles.size() > 0) {
					formFile = formFiles.get(0);
				}
			} else {// 制度类，需要套红，返回套红后的文件
				List<FormFile> formFiles = SDK.getBOAPI().getFiles(bo.getId(),
						"ZW");
				if (formFiles != null && !formFiles.isEmpty()
						&& formFiles.size() > 0) {
					formFile = formFiles.get(0);
				}
			}

			ConsolePrinter.info("reg_level_dict=" + reg_level_dict);
			ConsolePrinter.info("formFile=" + formFile);

			if (formFile != null) {
				DCContext dc = new DCContext(UserContext.fromUID("admin"),
						DCProfileManager.getDCProfile(formFile.getAppId(),
								"!iweboffice-"), formFile.getAppId(),
						formFile.getProcessInstId(), formFile.getBoItemName(),
						formFile.getFileName());
				if (dc != null) {
					ConsolePrinter.info("dcfilename=" + dc.getFileName());
					String awsForGrcNasPath = ODAppUtil.getAppParamValue(
							"com.whccb.apps.system.integration",
							"awsForGrcFilePath");
					String toGrcFilePath = awsForGrcNasPath
							+ bo.getString("FILE_PATH")
							+ bo.getString("DOC_NAME");
					ConsolePrinter.info("toGrcFilePath=" + toGrcFilePath);
					File toGrcFile = new File(toGrcFilePath);
					if (!toGrcFile.getParentFile().exists()) {// 检查目录是否存在
						toGrcFile.getParentFile().mkdirs();// 创建目录
					}
					// 创建文件
					if (toGrcFile.createNewFile()) {
						// 复制文件内容
						copyFile(SDK.getDCAPI().read(dc), toGrcFilePath);
						// 调用GRC接口，告知GRC系统
						ResponseObject ro = sendGrcRequest(toGrcXmlContext(bo));
						ConsolePrinter.info("ro=" + ro);
					}
				}

			}
			// DCContext dc = SDK.getBOAPI().getFileDCContext(formFile);
		}
	}

	private void copyFile(InputStream inStream, String newPath)
			throws Exception {
		int byteread = 0;
		if (inStream != null) {
			FileOutputStream fs = new FileOutputStream(newPath);
			byte[] buffer = new byte[inStream.available()];
			while ((byteread = inStream.read(buffer)) != -1) {
				fs.write(buffer, 0, byteread);
			}
			fs.close();
			inStream.close();
		}
	}

	private ResponseObject sendGrcRequest(String context) {
		String url = ODAppUtil.getAppParamValue(
				"com.whccb.apps.system.integration", "grcReceiveFileUrl");
		String sourceAppId = "com.whccb.apps.system.integration";
		String aslp = "aslp://com.whccb.apps.system.integration/wsyhSendRequest";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("url", url);
		params.put("content", context);
		ResponseObject ro = SDK.getAppAPI().callASLP(
				SDK.getAppAPI().getAppContext(sourceAppId), aslp, params);
		return ro;
	}

	private String toGrcXmlContext(BO bo) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
		Date date = new Date();
		String sn = SDK.getRuleAPI().executeAtScript(
				"@getFormCode(AWS,AWS-GRC-Receive,6)");
		ConsolePrinter.info("原来SN=" + sn);
		if (StringUtils.isNotEmpty(sn)) {
			sn = sn.substring(3);
		}
		ConsolePrinter.info("截取后SN=" + sn);
		StringBuffer result = new StringBuffer(
				"<?xml version=’1.0’ encoding=’UTF-8’?>");
		if (bo != null) {
			result.append("<service>");
			result.append("<SYS_HEAD>");
			result.append("<commCode>cc001</commCode>");
			result.append("<receiverId>grc</receiverId>");
			result.append("<senderDate>").append(dateFormat.format(date))
					.append("</senderDate>");
			result.append("<senderTime>").append(timeFormat.format(date))
					.append("</senderTime>");
			result.append("<senderId>aws</senderId>");
			result.append("<senderSN>").append(sn).append("</senderSN>");
			result.append("<tradeCode>GRC_R_0002</tradeCode>");
			result.append("</SYS_HEAD>");
			result.append("<BODY>");
			result.append("<reg_check_innid>")
					.append(bo.getString("REG_CHECK_INNID"))
					.append("</reg_check_innid>");
			result.append("<file_path>").append(bo.getString("FILE_PATH"))
					.append("</file_path>");
			result.append("<doc_name>").append(bo.getString("DOC_NAME"))
					.append("</doc_name>");
			result.append("<file_no>").append(bo.getString("FILENUM"))
					.append("</file_no>");
			result.append("</BODY>");
			result.append("</service>");
		}
		ConsolePrinter.info("result=" + result.toString());
		return result.toString();
	}

}
